//定义js命名空间
Ext.namespace('FsCarInfo.FsCarInventoryList');
//TODO : 完善数据结构
//DateTime -- date , decimal -- float
// { name: 'Department.Name', mapping: 'Department.Name' },
// { name: 'Department'},
//FsCarInventoryList FieldArray
FsCarInfo.FsCarInventoryList.BaseFieldsArray = new Array(
	{ name: 'Id', type: 'string' },
	{ name: 'InveId', type: 'string' },
	{ name: 'CarId', type: 'string' },
	{ name: 'Car' },
	{ name: 'Car.Brand', mapping: 'Car.Brand' },
	{ name: 'Car.Series', mapping: 'Car.Series' },
	{ name: 'Car.Model', mapping: 'Car.Model' },
	{ name: 'Car.Color', mapping: 'Car.Color' },
	{ name: 'Car.EnginId', mapping: 'Car.EnginId' },
	{ name: 'Car.FrameId', mapping: 'Car.FrameId' },
	{ name: 'State', type: 'int' },
	{ name: 'OperUserId', type: 'string' },
	{ name: 'OperUser.Name', mapping: 'OperUser.Name' },
	{ name: 'OperDate', type: 'string' },
	{ name: 'Version', type: 'int' }
);

//FsCarInventoryList JsonReader
FsCarInfo.FsCarInventoryList.JsonReader = Ext.extend(Infrastructure.BaseJsonReader, {
	constructor: function (cfg) {
		cfg = cfg || {};
		FsCarInfo.FsCarInventoryList.JsonReader.superclass.constructor.call(this, Ext.apply({
			fields: FsCarInfo.FsCarInventoryList.BaseFieldsArray
		}, cfg));
	}
});

//FsCarInventoryList JsonStore
FsCarInfo.FsCarInventoryList.JsonStore = Ext.extend(Infrastructure.BaseJsonStore, {
	constructor: function (cfg) {
		cfg = cfg || {};
		FsCarInfo.FsCarInventoryList.JsonStore.superclass.constructor.call(this, Ext.apply({
			url: '/FsCarInventoryList/GetPlist',
			params: {
				start: 0,
				limit: ALL_PAGESIZE_SETTING
			},
			remoteSort: true,
			fields: FsCarInfo.FsCarInventoryList.BaseFieldsArray,
			listeners: {
				'remove': function (thiz, record, index) {
					Ext.Ajax.request({
						url: '/FsCarInventoryList/Delete?Id=' + record.data.Id,
						success: function (response, opts) {
							var result = Ext.util.JSON.decode(response.responseText);
							if (result.success == false) {
								JsHelper.ShowError(result.msg);
								this.insert(0, record);
							}
						}
					});
				}
			}
		}, cfg));
	}
});

//车辆盘点状态
FsCarInfo.FsCarInventoryList.StateStore = new Ext.data.ArrayStore({
	id: 0,
	fields: [
		'Code',
		'Name'
	],
	data: [['0', '未盘点'], ['1', '已盘点']]
});

//FsCarInventoryList GridPanel
FsCarInfo.FsCarInventoryList.GridPanel = Ext.extend(Ext.grid.GridPanel, {
	// User property
	//基本处理Url
	baseUrl: '/FsCarInventoryList/',
	//提交保存Url
	formSubmitUrl: '/FsCarInventoryList/SaveOrUpdate',
	//提交保存提示信息
	formSubmitMsg: '确定要保存吗?',
	//工具栏标签
	tbarMask: '11111111111111111',
	//表格列默认显示
	columnMask: '012345600001230000090123000000',
	//状态
	itemState: '',
	//盘点单
	inventoryId: '',

	// Property
	stripeRows: true,
	frame: true,
	border: true,
	layout: 'fit',
	loadMask: true,
	enableColumnMove: false,
	viewConfig: {
		autoFill: true
	},
	store: new FsCarInfo.FsCarInventoryList.JsonStore(),
	stateful: true,
	stateId: 'FsCarInfo.FsCarInventoryList.GridPanel',

	//constructor
	initComponent: function () {
		//prepare

		var itemGrid = this;
		var tbarMask = this.tbarMask;
		var colMask = this.columnMask;
		var cmdAddEntity = this.onAddEntity;
		var cmdDeleteEntity = this.onDeleteEntity;
		var cmdLoadEntity = this.onLoadEntity;
		var cmdQueryList = this.onQueryList;
		//双击
		var onRowDbClick = function (grid, rowIndex, e) {
			this.onLoadEntity(grid.store.getAt(rowIndex));
		}
		//盘点文件上传
		var cmdToFileUpload = this.toFileUpload;
		//提交审批
		var cmdTbarCmd = function () {
			this.tbarSubmit(this.baseUrl + 'MethodName', '确定要提交吗?', '您的信息提交到系统..');
		};
		//set store params
		this.store.setBaseParam('state', this.itemState);
		this.store.setBaseParam('inventoryId', this.inventoryId);

		// The filter.
		var gridFilter = new Ext.ux.grid.GridFilters({
			encode: true,
			filters: [
				{ dataIndex: 'Car.Brand', type: 'list', options: JsHelper.GetFilterListData(FsCarInfo.Params.CarBrandStore.data.items, 'Name', 'Name') },
				{ dataIndex: 'Car.Series', type: 'list', options: JsHelper.GetFilterListData(FsCarInfo.Params.CarSeriesStore.data.items, 'Name', 'Name') },
				{ dataIndex: 'Car.Model', type: 'list', options: JsHelper.GetFilterListData(FsCarInfo.Params.CarModelStore.data.items, 'Name', 'Name') },
				{ dataIndex: 'Car.Color', type: 'list', options: JsHelper.GetFilterListData(FsCarInfo.Params.CarColorStore.data.items, 'Name', 'Name') },
				{ dataIndex: 'Car.EnginId', type: 'string' },
				{ dataIndex: 'Car.FrameId', type: 'string' },
				{ dataIndex: 'State', type: 'list', options: FsCarInfo.FsCarInventoryList.StateStore.reader.arrayData },
				{ dataIndex: 'OperUser.Name', type: 'string' },
				{ dataIndex: 'OperDate', type: 'date' }
			]
		});

		var bandStore = new Infrastructure.DictJsonStore({
			category: 'Brand'
		});

		bandStore.load({
			callback: function (r) {
				gridFilter.addFilter({
					type: 'list',
					dataIndex: 'CurrentDep',
					options: JsHelper.GetFilterListData(r, 'Code', 'Name')
				});
			}
		});

		// selModel
		var selModel = new Ext.grid.CheckboxSelectionModel({
			//header: '',
			//singleSelect: true,
			menuDisabled: true,
			listeners: {
				'selectionchange': function (sm) {
					// 控制工具栏按钮是否可用
					itemGrid.delBtn.setDisabled(sm.getCount() < 1);
				}
			}
		});

		// columnModel 对于不常需要显示的 hidden: true 
		var gridColumn = new Ext.grid.ColumnModel({
			columns: [
				new Ext.grid.RowNumberer(),
				selModel,
				{ header: '品牌', dataIndex: 'Car.Brand' },
				{ header: '系列', dataIndex: 'Car.Series' },
				{ header: '型号', dataIndex: 'Car.Model' },
				{ header: '颜色', dataIndex: 'Car.Color' },
				{ header: '发动机号', dataIndex: 'Car.EnginId', hidden: true },
				{ header: '车架号', dataIndex: 'Car.FrameId' },
				{ header: "状态", dataIndex: 'State', hidden: this.columnMask.charAt(1) == '0',
					renderer: function (v) {
						return v == null ? "未盘点" : FsCarInfo.FsCarInventoryList.StateStore.getById(v).get('Name');
					}
				},
				{ header: "盘点用户", dataIndex: 'OperUser.Name', hidden: this.columnMask.charAt(1) == '0' },
				{ header: "盘点时间", dataIndex: 'OperDate', hidden: this.columnMask.charAt(1) == '0' }
			],
			defaults: {
				sortable: true,
				menuDisabled: false
			}
		});

		// PageBar
		var pagebBar = new Infrastructure.BasePagingToolbar({
			store: this.store,
			plugins: this.plugins
		});

		// 常用工具栏
		var toolBar = new Ext.Toolbar({
			items: [{
				xtype: 'tbardelbtn',
				hidden: this.tbarMask.substring(0, 1) == '0',
				handler: cmdDeleteEntity,
				hidden: true,
				scope: itemGrid
			}, {
				xtype: 'tbbutton',
				minWidth: 80,
				ref: '../btnToApprove',
				text: '条码盘点',
				cls: 'x-btn-text-icon',
				hidden: this.tbarMask.substring(1, 2) == '0',
				icon: '/Content/icons/application_get.png',
				handler: cmdToFileUpload,
				scope: itemGrid
			}, {
				xtype: 'tbbutton',
				minWidth: 80,
				ref: '../btnToApprove',
				text: '二维码盘点',
				cls: 'x-btn-text-icon',
				hidden: this.tbarMask.substring(1, 2) == '0',
				icon: '/Content/icons/application_get.png',
				handler: cmdToFileUpload,
				scope: itemGrid
			}, '-', {
				xtype: 'textfield',
				width: 150,
				id: 'q_query'
			}, {
				xtype: 'tbarqrybtn',
				handler: cmdQueryList,
				scope: itemGrid
			}, '-']
		});

		Ext.apply(this, {
			plugins: [gridFilter],
			sm: selModel,
			cm: gridColumn,
			tbar: toolBar,
			bbar: pagebBar,
			listeners: {
				'rowdblclick': onRowDbClick
			}
		});

		FsCarInfo.FsCarInventoryList.GridPanel.superclass.initComponent.call(this);
	},

	/****************** 
	* user function 
	******************/

	// 添加
	onAddEntity: function () {
		var itemGrid = this;
		var itemEditForm = new FsCarInfo.FsCarInventoryList.EditForm({
			listeners: {
				'afterSave': function (ele, rt) {
					if (rt) {
						ele.form.reset();
						var itemGridStore = itemGrid.store;
						itemGridStore.reload();
						JsHelper.ShowInfo('添加信息成功!');
					}
				}
			}
		});
		var itemEditWin = new FsCarInfo.FsCarInventoryList.EditWin({
			items: [itemEditForm]
		});
		itemEditWin.show();
	},

	// 读取车辆信息显示
	onLoadEntity: function (selRecord) {
		var selId = selRecord.data.Id;
		var carStore = new FsCarInfo.FsCarbaseinfo.JsonStore();
		var carRecord = new carStore.recordType(selRecord.data.Car);

		var itemCarInfoForm = new FsCarInfo.FsCarbaseinfo.EditForm({
			submitUrl: '',
			Id: carRecord.data.Id,
			dataRecord: carRecord
		});
		var itemEditWin = new Ext.Window({
			title: '商品车信息',
			iconCls: 'car',
			width: 600,
			resizable: false,
			constrain: true,
			autoHeight: true,
			modal: true,
			closeAction: 'close',
			plain: true,
			buttonAlign: 'center',
			items: [itemCarInfoForm]
		});
		itemEditWin.show();
		itemCarInfoForm.form.loadRecord(carRecord);
	},

	// 删除
	onDeleteEntity: function () {
		var itemGrid = this;
		var itemGridStore = this.store;
		JsHelper.DelConfirm(function (btn) {
			if (btn == 'yes') {
				var s = itemGrid.getSelectionModel().getSelections();
				for (var i = 0, r; r = s[i]; i++) {
					itemGridStore.remove(r);
				}
			}
		});
	},

	// 查询
	onQueryList: function () {
		var itemGrid = this;
		var q_query = Ext.getCmp('q_query').getValue();
		itemGrid.store.load({
			params: {
				start: 0,
				limit: ALL_PAGESIZE_SETTING,
				q_query: q_query
			}
		})
	},

	// 盘点文件上传
	toFileUpload: function () {
		var itemGrid = this;
		var fpWin = new Infrastructure.FileUploadWin({
			uploadUrl: '/FsCarInventory/InventoryFileUpload?Id=' + this.inventoryId,
			listeners: {
				'uploadSuccess': function (ele, rt) {
					if (rt) {
						var itemGridStore = itemGrid.store;
						itemGridStore.reload();
					}
				}
			}
		});
		fpWin.show();
	},

	// 提交选定记录..
	tbarSubmit: function (submitUrl, confirmMsg, successMsg) {
		var itemGrid = this;
		var selRecord = this.getSelectionModel().getSelected();
		if (selRecord == null) {
			JsHelper.ShowError('未选择记录.');
			return -1;
		}
		var selId = selRecord.data.Id;
		JsHelper.Confirm(confirmMsg, function (btn) {
			if (btn == 'yes') {
				var ids = [];
				var s = itemGrid.getSelectionModel().getSelections();
				for (var i = 0, r; r = s[i]; i++) {
					ids.push(r.data.Id);
				}
				//加载进度条
				Ext.MessageBox.show({
					msg: '正在提交数据到中心服务器...',
					progressText: '保存数据...',
					width: 300,
					wait: true,
					waitConfig: { interval: 1000 }
				});
				Ext.Ajax.request({
					url: submitUrl,
					params: {
						'Ids': ids.toString()
					},
					success: function (response, opts) {
						Ext.MessageBox.hide();
						var result = Ext.util.JSON.decode(response.responseText);
						if (result.success == false) {
							JsHelper.ShowError('操作失败:' + result.msg);
						} else {
							itemGrid.store.reload();
							Ext.Msg.alert('提示,操作成功', '成功。' + successMsg);
						}
					},
					failure: function (form, action) {
						Ext.MessageBox.hide();
						JsHelper.ShowError('系统异常:' + action.result.msg);
					}
				});
			}
		});
	}
});
